<?php

App::import('Vendor', 'lessc', array('file' => 'lessphp'.DS.'lessc.inc.php'));

class StylevarsController extends AppController {

    var $name = 'Stylevars';
    
    var $variable_collects = array(
    	array(
	    	'id'=>'tab-colors',
    		'name'=>'色调',
	    	'items' => array(
	    			array(
	    					'name'=>'调色板',
	    					'varis' => array(
	    							'gray-darker','gray-dark','gray','gray-light','gray-lighter','-',
	    							'brand-primary','brand-success','brand-info','brand-warning','brand-danger',
	    							'component-active-color','component-active-bg',
	    			
	    							'body-bg','text-color',
	    							'link-color','link-hover-color',
	    			
	    					),
	    			),
	    	),
    	),
    	array(
    		'id'=>'tab-basic',
    		'name'=>'基本设置',
	    	'items' => array(
	    			array(
	    					'name'=>'栅格',
	    					'varis' => array('grid-columns','grid-gutter-width',
	    							'grid-float-breakpoint','',''
	    					),
	    			),
	    			array(
	    					'name'=>'基本样式',
	    					'varis' => array(
	    							'','',''
	    							,'line-height-base','line-height-computed','line-height-large','line-height-small',
	    					),
	    			),
                    array(
                            'name'=>'页面宽度',
                            'varis' => array(
                                    'container-desktop','container-large-desktop','container-lg'
                                    ,'container-lg-desktop','container-md','container-sm','container-tablet',
                            ),
                    ),
	    			array(
	    					'name'=>'字体',
	    					'varis' => array('font-family-sans-serif','font-family-serif',
	    							'font-family-monospace','font-family-base',
	    							'font-size-base','font-size-large','font-size-small',
	    					),
	    			),
	    			
	    			array(
	    					'name'=>'边距',
	    					'varis' => array(
	    							'padding-base-vertical','padding-large-vertical','padding-small-vertical',
	    							'padding-base-horizontal','padding-large-horizontal','padding-small-horizontal',
	    							'padding-xs-vertical','padding-xs-horizontal',''
	    					),
	    			),
	    			array(
	    					'name'=>'边框圆角',
	    					'varis' => array('border-radius-base','border-radius-large',
	    							'border-radius-small','',''
	    					),
	    			),
	    			
	    			array(
	    					'name'=>'表格',
	    					'varis' => array('table-cell-padding','table-condensed-cell-padding',
	    							'table-bg','table-bg-accent','table-bg-hover'
	    							,'table-bg-active','table-border-color'
	    					),
	    			),
	    			array(
	    					'name'=>'标题栏heading',
	    					'varis' => array(
	    							'headings-font-family','headings-font-weight',
	    							'headings-line-height','headings-color',
	    					),
	    			),
	    			array(
	    					'name'=>'区域面板',
	    					'varis' => array(
	    							'panel-bg','panel-footer-bg','panel-default-heading-bg','panel-default-border',
	    							'panel-body-padding','panel-default-text'
	    					),
	    			),
	    	),
    	),
    	
    	
    	array(
    		'id'=>'tab-tips',
    		'name'=>'提示与对话框',
    		'items' => array(
    				array(
    						'name'=>'气泡提示',
    						'varis' => array(
    								'popover-bg','popover-title-bg','popover-border-color',
    								'popover-max-width',
    								'popover-arrow-width','popover-arrow-color',
    						),
    				),
    				array(
    						'name'=>'状态',
    						'varis' => array(
    								'state-success-text','state-success-bg','state-success-border',
    								'state-warning-text','state-warning-bg','state-warning-border',
    								'state-danger-text','state-danger-bg','state-danger-border'
    						),
    				),
    				array(
    						'name'=>'弹窗modals',
    						'varis' => array(
    								'modal-inner-padding','modal-title-padding',
    								'modal-title-line-height',
    								'modal-content-bg','modal-lg','modal-md'
    								,'modal-sm'
    						),
    				),
    		)
    	),
    	array(
    		'id'=>'tab-form',
    		'name'=>'表单与按钮',
    		'items' => array(
    				array(
    						'name'=>'表单',
    						'varis' => array('input-bg','input-bg-disabled',
    								'input-color','input-border-focus','input-color-placeholder'
    								,'input-height-base','input-height-large','input-height-small','',
    						),
    				),
    		),
    	),
    		
    		
    		
    		
    		
    );
    
    public function admin_savetheme(){
    	$styleid = Configure::read('Site.style');
    	if(empty($styleid)){
    		$this->loadModel('Style');
    		$this->Style->save(array('name'=>date('Y-m-d H:i')));
    		$styleid = $this->Style->getLastInsertID();
    	}
    	$this->loadModel('Stylevar');
    	$styles = $this->Stylevar->find('all',array('conditions'=>array('styleid'=>$styleid)));
    	foreach($styles as $k => &$s){
    		$sk = $s['Stylevar']['skey'] ;
    		if(isset($_POST['data'][$sk]) && $s['Stylevar']['sval'] != $_POST['data'][$sk]){
//     			echo "===$sk==={$s['Stylevar']['sval']} != {$_POST['data'][$sk]}=======\n";
    			$s['Stylevar']['sval'] = $_POST['data'][$sk];
    		}
    		else{
    			unset($styles[$k]); //无提交项或者无更改时，取消项。save时不处理
    		}
    		unset($_POST['data'][$sk]);
    	}
    	/* post中可能存在数据库里不存在的新增项 */
    	foreach($_POST['data'] as $k => $v){
    		$styles[] = array('Stylevar'=>array('styleid'=>$styleid,'skey'=>$k,'sval'=>$v));
    	}
//     	print_r($styles);exit;
    	if(!empty($styles)){
    		$this->Stylevar->saveAll($styles);
    		$successinfo = array('success' => __('save success'));
    	}
    	else{
    		$successinfo = array('success' => __('no change.'));
    	}
    	echo json_encode($successinfo);
    	exit;
    }
    
    public function admin_themeroller(){
    	load_lang('less');
    	
    	$styleid = Configure::read('Site.style');
    	if(empty($styleid)){
    		$styleid=1;
    	}
    	$styles = $this->Stylevar->find('all',array('conditions'=>array('styleid'=>$styleid)));
    	//print_r($styles);
    	$variables = $values = array();
    	
    	foreach($styles as $style){
    		$variables[$style['Stylevar']['skey']] = $style['Stylevar']['sval'];
    	}
    	/* 合并post提交的变量  */
    	if(!empty($_POST['data'])){
    		foreach($_POST['data'] as $k=>$v){
    			if(empty($v)) unset($_POST['data'][$k]);
    		}
    		$variables = array_merge($variables,$_POST['data']);
    	}
    	/* 按最新的variable生成预编译的css文件  */
    	$tmp_css = '.css{';
    	foreach($variables as $k => $v){
    		$tmp_css .= $k.':'.$v.';';
    	}
    	$tmp_css .= '}';
    	
    	$this->set('variables',$variables);    	
    	$less = new lessc;
    	$less->setVariables($variables);

    	$compile_css = $less->compile($tmp_css);
    	if(preg_match_all('/([\w-]+):(.+?);/',$compile_css,$matches)){
    		foreach($matches[1] as $k => $v){
    			$values[$v] = trim($matches[2][$k]);
    		}
    	}
    	else{
    		echo "css complie preg_match error.";exit;
    	}
    	$this->set('values',$values);
    	$this->set('variable_collects',$this->variable_collects);
    }

    public function admin_get_variable(){
        $this->autoRender = false;
        if($_GET['styleid']){
            $styleid = intval($_GET['styleid']);
        }
        else{
            $styleid = Configure::read('Site.style');
        }
        if(empty($styleid)){
            $styleid=1;
        }
        $cachekey = 'bootstrap_style_'.$styleid;
        $css_content =Cache::read($cachekey);
        if($css_content === false || !empty($_POST['data']) ){
            $styles = $this->Stylevar->find('all',array('conditions'=>array('styleid'=>$styleid)));
            $variables = array();
            foreach($styles as $style){
                $variables[$style['Stylevar']['skey']] = $style['Stylevar']['sval'];
            }
            /* 合并post提交的变量  */
            if(!empty($_POST['data'])) {
                foreach($_POST['data'] as $k=>$v) {
                    if(empty($v)) unset($_POST['data'][$k]);
                }
                $variables = array_merge($variables,$_POST['data']);
            }
            foreach($variables as $k => $v) {
                $variables_content .= '@'.$k."\t\t".$v.";\r\n";
            }
            $variables_content = "// generate at ".date('Y-m-d H:i:s')." by miaocms.\n\n".$variables_content;
            header("Content-disposition: attachment; filename=bootstrap.variables.less");
            header("Content-Type: application/force-download");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".strlen($variables_content));
            header("Pragma: no-cache");
            header("Expires: 0");
            echo $variables_content;
            exit;
        }
    }
    /**
     *
     * @param unknown_type $type  responsive for phone and bootstrap for web.
     */
    public function admin_getcss(){
    	if($_GET['styleid']){
    		$styleid = intval($_GET['styleid']);
    	}
    	else{
    		$styleid = Configure::read('Site.style');
    	}
    	if(empty($styleid)){
    		$styleid=1;
    	}
    	$cachekey = 'bootstrap_style_'.$styleid;
    	$css_content =Cache::read($cachekey);
    	if($css_content === false || !empty($_POST['data']) ){
	    	$styles = $this->Stylevar->find('all',array('conditions'=>array('styleid'=>$styleid)));
	    	$variables = array();
	    	foreach($styles as $style){
	    		$variables[$style['Stylevar']['skey']] = $style['Stylevar']['sval'];
	    	}
	    	/* 合并post提交的变量  */
	    	if(!empty($_POST['data'])){
	    		foreach($_POST['data'] as $k=>$v){
	    			if(empty($v)) unset($_POST['data'][$k]);
	    		}
	    		$variables = array_merge($variables,$_POST['data']);
	    	}
// 	    	print_r($variables);exit;
	    	
	    	$less = new lessc;
	    	// $less->setFormatter("compressed");//lessjs compressed classic
	    	$less->setImportDir(array(ROOT.'/data/less/'));
	    	$less->setVariables($variables);
	    	$css_content = $less->compileFile(ROOT.'/data/less/miaocms.less');
	    	$css_content = preg_replace('/url\(["|\']?(.+?)["|\']?\)/ies',"'url('.\$this->fixurl('\\1').')'",$css_content);
	    	if(empty($_POST['data'])){	//无post提交内容时，才写缓存。
	    		Cache::write($cachekey,$css_content);
	    	}
	    	elseif($_POST['submit-type'] == 'download'){
	    		$css_content = "/** generate at ".date('Y-m-d H:i:s')." by miaocms. **/".$css_content;
	    		header("Content-disposition: attachment; filename=bootstrap.min.css");
	    		header("Content-Type: application/force-download");
	    		header("Content-Transfer-Encoding: binary");
	    		header("Content-Length: ".strlen($css_content));
	    		header("Pragma: no-cache");
	    		header("Expires: 0");
	    		echo $css_content;
	    		exit;
	    	}
	    	else{ //有post提交时，均为编辑预览时临时性的style
	    		$cssfile = 'themeroller_'.guid_string($variables).'.css';
	    		if(defined('IN_SAE') || is_writable(WEB_VISIT_CACHE)){
	    			file_put_contents(WEB_VISIT_CACHE.$cssfile, $css_content);
	    			echo '<link flag="themeroller" href="'.WEB_VISIT_CACHE_URL.$cssfile.'" type="text/css" rel="Stylesheet" />';
	    		}
	    		else{
	    			echo WEB_VISIT_CACHE." is not writeable.";
	    		}
	    		exit;
	    	}
    	}
    	header('Content-Type:text/css');
    	echo $css_content;
    	exit;
    }
    

    private function fixurl($url,$path = CSS){
    	if(substr($url,0,4)=='/img'){ // 已/img 开头，IMAGES_URL计算img所在的二级目录，img的二级目录和程序的二级目录不一样。如manage何img共用一个img目录
    		return str_replace('//','/',dirname(IMAGES_URL).$url);
    	}
    	while(substr($url,0,3)=='../'){
    		$path = dirname($path);
    		$url = substr($url,3);
    		if($path.DS == WWW_ROOT){
    			return str_replace('//','/',dirname(IMAGES_URL).'/'.$url);
    		}
    	}
    	$path = str_replace(WWW_ROOT, '', $path);
    	$path = str_replace(array('\\','//'), '/', $path);
    	return $url = str_replace('//','/',dirname(CSS_URL).'/'.$path.'/'.$url); // css的相对路径，计算CSS_URL所在的二级目录
    }

    private function _import_by_viriables($styleid,$content){
    	$vars = explode("\n",$content);
    	foreach($vars as $line){
    		$line = trim(preg_replace('/\/\/.*$/','',$line)); // 去掉注释内容
    		$line = preg_replace('/;.*$/','',$line); // 去掉“;”及其后的内容
    	
    		$var = explode(':',$line);
    		//echo $line."\n";
    		if(count($var)==2){
    			if(substr($var[0],0,1)=='@'){
    				$var[0] = substr($var[0],1);
    			}
    			$data = array();
    			$data['skey']=trim($var[0]);
    			$data['sval']=trim($var[1]);
    			$data['styleid']=$styleid;
    			$hasgot = $this->Stylevar->find('first',array('conditions'=>array('skey'=>$data['skey'],'styleid'=>$styleid)));
    			if(!empty($hasgot)){
    				$this->Stylevar->id = $hasgot['Stylevar']['id'];
    				$hasgot['Stylevar']['sval'] = $data['sval'];
    				$hasgot = $this->Stylevar->save($hasgot);
    			}
    			else{
    				$this->Stylevar->create();
    				$hasgot = $this->Stylevar->save($data);
    			}
    		}
    	}
    	Cache::delete('bootstrap_style_'.$styleid);
    }
    public function admin_import($styleid=161){
    	echo $variable_file = ROOT.'/'.'data/bootstrap/less/variables.less';
    	$content = file_get_contents($variable_file);
    	$this->_import_by_viriables($styleid,$content);
    	echo json_encode(array('success'=>'import success.'));
    	exit;
    }
	
    /**
     * 传入styleid的参数值 
     * @see AppController::admin_edit()
     */
    public function admin_edit($styleid, $copy = NULL){
    	load_lang('less');
    	if(!empty($this->data['Style'])){
    		if(!empty($this->data['Style']['variables'])){
    			$variable_file = $this->data['Style']['variables']['tmp_name'];
    			if(file_exists($variable_file)){
	    			$content = file_get_contents($variable_file);
	    			$this->_import_by_viriables($styleid,$content);
    			}
    		}
    		$this->loadModel('Style');
    		$this->Style->save($this->data['Style']);
    		
    		$successinfo = array('success' => __('edit success'));
    		echo json_encode($successinfo);
    		exit;
    	}
    	elseif(!empty($this->data['Stylevar'])){
			$this->Stylevar->saveAll($this->data['Stylevar']);
			$successinfo = array('success' => __('edit success'));
    		echo json_encode($successinfo);
			exit;
    	}
    	$this->loadModel('Style');
    	$this->data = $this->Style->find('first',array('conditions'=>array('id'=>$styleid)));
    	
    	$styles = $this->Stylevar->find('all',array('conditions'=>array('styleid'=>$styleid)));
    	$this->set('styles',$styles);
    	$this->set('styleid',$styleid);
    }

}

?>